//
//  HotColdSignalViewController.m
//  RACExample
//
//  Created by 山刘 on 2020/5/29.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "HotColdSignalViewController.h"
// 简单的HTTP请求工具
@interface iosHttp : NSObject
@property(nonatomic,strong) AFHTTPSessionManager *sessionManager;

-(void)requestNetworkDataWithUrlString:(NSString*)urlString Params:(NSDictionary*)params completed:(void(^)(id response,NSError * error))completed;
-(RACSignal*)rac_requestNetworkDataWithUrlString:(NSString*)urlString Params:(NSDictionary*)params;
@end
@implementation iosHttp
-(instancetype)init{
    if (self == [super init]) {
        _sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://beta.uhomecp.com"]];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    return self;
}

/// 普通的网络请求功能
-(void)requestNetworkDataWithUrlString:(NSString*)urlString Params:(NSDictionary*)params completed:(void(^)(id response,NSError * error))completed{
    [self.sessionManager GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completed(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completed(nil,error);
    }];
}

/// 通过RAC处理过的网路请求
-(RACSignal*)rac_requestNetworkDataWithUrlString:(NSString*)urlString Params:(NSDictionary*)params{
    @weakify(self)
    RACSignal *fetchData = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self)
        
        NSURLSessionDataTask *task = [self.sessionManager GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error.localizedDescription);
             [subscriber sendError:error];
        }];
        
        return [RACDisposable disposableWithBlock:^{
            if (task.state != NSURLSessionTaskStateCompleted) {
                [task cancel];
            }
        }];
    }];
    return fetchData;
}
@end

/*================================================================================================================================================================*/

@interface HotColdSignalViewModel : NSObject
@property(nonatomic,strong) iosHttp *iosHttpRequest;

-(void)requestNetworkDataWithcompleted:(void(^)(id response,NSError * error))completed;
-(void)rac_requestNetworkData;
@end

@implementation HotColdSignalViewModel
-(void)requestNetworkDataWithcompleted:(void(^)(id response,NSError * error))completed {
    [self.iosHttpRequest requestNetworkDataWithUrlString:@"/cms-api/isShowAdvert" Params:@{@"code":@"13"} completed:^(id response, NSError *error) {
        completed(response,error);
    }];
}

-(void)rac_requestNetworkData{
//    RACSignal *serverSignalData = [self.iosHttpRequest rac_requestNetworkDataWithUrlString:@"/cms-api/isShowAdvert" Params:@{@"code":@"13"}];
//    RACSignal *titleSignalData = [serverSignalData flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
//        if ([value[@"code"] isKindOfClass:[NSString class]]) {
//            return [RACSignal return:value[@"code"]];
//        } else {
//            return [RACSignal error:[NSError errorWithDomain:@"some error" code:400 userInfo:@{@"originData": value}]];
//        }
//    }];
}

#pragma mark - getter
-(iosHttp *)iosHttpRequest{
    if (!_iosHttpRequest) {
        _iosHttpRequest = [[iosHttp alloc]init];
    }
    return _iosHttpRequest;
}
@end

@interface HotColdSignalViewController ()
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property(nonatomic,strong) HotColdSignalViewModel *viewModel;
@end

@implementation HotColdSignalViewController
/*
 需求1:
    请求网络数据,根据下发数据字段的 code msg 的不同来进行不同展示。
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    @weakify(self)
//    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        @strongify(self)
//        [self.viewModel requestNetworkDataWithcompleted:^(id response, NSError *error) {
//            if (response) {
//                NSLog(@"Normal Http Request: %@",response);
//            }
//        }];
//    }];
    
    [self test_Signal];
}

-(HotColdSignalViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[HotColdSignalViewModel alloc]init];
    }
    return _viewModel;
}

-(void)test_RACSubject{
    // Create a RACSubject signal
    RACSubject *subject = [RACSubject subject];
    NSLog(@"create Signal");
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:0.1 schedule:^{
        //Subscriber1
        [subject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 1 get a next value: %@ from subject", x);
        }];
        //Subscriber2
        [subject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 2 get a next value: %@ from subject", x);
        }];
    }];
    
    // Send Signals
    [[RACScheduler mainThreadScheduler] afterDelay:1 schedule:^{
        [subject sendNext:@"subject send package 1"];
    }];
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:1.1 schedule:^{
        //Subscriber3
        [subject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 3 get a next value: %@ from subject", x);
        }];
        
        //Subscriber4
        [subject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 4 get a next value: %@ from subject", x);
        }];
       
    }];
    
    // Send Signals
    [[RACScheduler mainThreadScheduler] afterDelay:2 schedule:^{
        [subject sendNext:@"subject send package 2"];
    }];
}

-(void)test_RACReplaySubject{
    // Create an RACReplaySubject signals
    RACSubject *replaySubject = [RACReplaySubject subject];
    NSLog(@"create Signal");
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:0.1 schedule:^{
        //Subscriber1
        [replaySubject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 1 get a next value: %@ from replay subject", x);
        }];
        
        //Subscriber2
        [replaySubject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 2 get a next value: %@ from replay subject", x);
        }];
    }];
    
    // Send Signals
    [[RACScheduler mainThreadScheduler] afterDelay:1 schedule:^{
        [replaySubject sendNext:@"replaySubject send package 1"];
    }];
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:1.1 schedule:^{
        //Subscriber3
        [replaySubject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 3 get a next value: %@ from replay subject", x);
        }];
        
        //Subscriber4
        [replaySubject subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 4 get a next value: %@ from replay subject", x);
        }];
    }];
    
    // Send Signals
    [[RACScheduler mainThreadScheduler] afterDelay:2 schedule:^{
        [replaySubject sendNext:@"replaySubject send package 2"];
    }];
}

-(void)test_Signal{
    // Create an RACReplaySubject signals
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        // Send Signals
        [[RACScheduler mainThreadScheduler] afterDelay:1 schedule:^{
            [subscriber sendNext:@"replaySubject send package 1"];
        }];
        // Send Signals
        [[RACScheduler mainThreadScheduler] afterDelay:2 schedule:^{
            [subscriber sendNext:@"replaySubject send package 2"];
        }];
        return [RACDisposable disposableWithBlock:^{
            NSLog(@"disposable");
        }];
    }];
    NSLog(@"create Signal");
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:0.1 schedule:^{
        //Subscriber1
        [signal subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 1 get a next value: %@ from replay subject", x);
        }];
        
        //Subscriber2
        [signal subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 2 get a next value: %@ from replay subject", x);
        }];
    }];
    
    // Subscribe the signal
    [[RACScheduler mainThreadScheduler] afterDelay:1.1 schedule:^{
        //Subscriber3
        [signal subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 3 get a next value: %@ from replay subject", x);
        }];
        
        //Subscriber4
        [signal subscribeNext:^(id  _Nullable x) {
            NSLog(@"Subscriber 4 get a next value: %@ from replay subject", x);
        }];
    }];
}
@end
